﻿using System.IO;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.ServiceHosting.ServiceRuntime;
using System.ServiceModel.Syndication;
using System.Xml;
using System;

namespace RSSAggregator_WebRole
{
    public class AgregatorService : IAgregatorService
    {
        public Rss20FeedFormatter GetRssFeeds(string category, string feedName)
        {
            SyndicationFeed feed = getSyndicationFeedFromBlob(category, feedName);
            return feed.GetRss20Formatter();
        }

        public Atom10FeedFormatter GetAtomFeeds(string category, string feedName)
        {
            SyndicationFeed feed = getSyndicationFeedFromBlob(category, feedName);
            return feed.GetAtom10Formatter();
        }

        private BlobContainer container;

        private BlobContainer GetContainer(string containerName)
        {
            BlobStorage blobStorage = BlobStorage.Create(StorageAccountInfo.GetDefaultBlobStorageAccountFromConfiguration());
            BlobContainer newContainer = blobStorage.GetBlobContainer(containerName);

            newContainer.CreateContainer(null, ContainerAccessControl.Public);
            this.container = newContainer;
            return newContainer;
        }

        private SyndicationFeed getSyndicationFeedFromBlob(string category, string feedName)
        {
            string PathToFile = GetTempRssFile(category);
            //FileStream rssStream = new FileStream(PathToFile, FileMode.Create,FileAccess.ReadWrite);
            MemoryStream memory = new MemoryStream();
            BlobContents contents = new BlobContents(memory);

            BlobProperties properties = this.container.GetBlob(feedName,contents,false);
            memory.Flush();
            memory.Close();

            XmlReader reader = XmlReader.Create(properties.Uri.ToString());
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            reader.Close();

            return feed;
        }

        private string GetTempRssFile(string category)
        {
            GetContainer(category);

            ILocalResource myIO = RoleManager.GetLocalResource("rssrepository");
            string tempfile = String.Format("rss{0}.xml",DateTime.Now.ToShortTimeString().Replace('/','-').Replace(':','-'));
            return Path.Combine(myIO.RootPath, tempfile);
        }

        //private SyndicationFeed getSyndicationFeedFromBlob(string feedName)
        //{
        //    string PathToFile = GetTempRssFile();
        //    StoreFeedToIsolateStorage(feedName);

        //    XmlReader reader = XmlReader.Create(PathToFile);
        //    SyndicationFeed feed = SyndicationFeed.Load(reader);
        //    reader.Close();
        //    return feed;
        //}

    }
}
